package view.Core;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import method.GPS.UseGPS_BActivity;
import method.searchSQL.criteriaControl;
import method.searchSQL.distControl;
import method.searchSQL.orderTreeID;
import method.searchSQL.statusControl;
import method.searchSQL.typeControl;

import org.apache.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;

public class treeDataUpdate extends Activity implements
		AdapterView.OnItemSelectedListener {
	String treeID ;
	private static final int REQUEST_CODE = 1234;

	private Button buttonUpdate, getLongitudeAndLatitudeButton;
	private TextView textViewDist;
	private String databaseURL;
	private String x, y;
	private String dRegistrationDate;
	orderTreeID oID;

	statusControl i = new statusControl();
	ArrayList statusSpinneritems = new ArrayList();

	distControl d = new distControl();
	ArrayList distSpinneritems = new ArrayList();

	typeControl t = new typeControl();
	ArrayList typeSpinneritems = new ArrayList();

	criteriaControl c = new criteriaControl();
	ArrayList criteriaSpinneritems = new ArrayList();

	// insertTree it;

	EditText editTreeID, editDBH, editHeight, editCrownSpread,
			editEstimatedAge, editLocation, editLongitude, editLatitude;
	TextView selection;

	String currentdistNo, currentStatusID, currenttypeID, currentcrID;

	String URL;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.update_menu);

		findViewByID();

		//buttonUpdate.setText("Update");
		final Spinner spin = (Spinner) findViewById(R.id.statusSpinner);
		final Spinner distSpin = (Spinner) findViewById(R.id.distSpinner);
		final Spinner typeSpin = (Spinner) findViewById(R.id.typeSpinner);
		final Spinner criteriaSpin = (Spinner) findViewById(R.id.criteriaSpinner);
		Button buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
		
	    Bundle bunde = this.getIntent().getExtras();
	    treeID = bunde.getString("treeID");
		
		selectAllFromDB();

		URL = getResources().getString(R.string.serverURL) + "insert.php";

		// /status[
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getStatus.php";
//statusID 	status 	description
		/*
		String statusIDV = selectAllByID("status", "statusID", currentStatusID, "statusID");
		String statusV = selectAllByID("status", "statusID", currentStatusID, "status");
		String descriptionV = selectAllByID("status", "statusID", currentStatusID, "description");
		*/
		String statusIDV = selectAllByID("status", "statusID", "STA01", "statusID");
		String statusV = selectAllByID("status", "statusID", "STA01", "status");
		String descriptionV = selectAllByID("status", "statusID", "STA01", "description");
		i.addCurrentStatus(statusIDV, statusV, descriptionV);
		//i.addCurrentStatus("x", "y", "z");
		i.addStatus(databaseURL);

		for (int spinnerI = 0; spinnerI < i.getSize(); spinnerI++) {
			statusSpinneritems.add(i.getStatus(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> statusAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, statusSpinneritems);
		statusAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(statusAA);
		// /]status


		// /dist[distNo 	distName
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getDist.php";
		
		String distNoV = selectAllByID("district", "distNo", currentdistNo, "distNo");
		String distNameV = selectAllByID("district", "distNo", currentdistNo, "distName");
		
		d.addCurrentDist(distNoV, distNameV);
		d.addDist(databaseURL);

		for (int spinnerI = 0; spinnerI < d.getSize(); spinnerI++) {
			distSpinneritems.add(d.getDist(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> DistAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, distSpinneritems);
		DistAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		distSpin.setAdapter(DistAA);
		// /]dist

		// /[type typeID 	typeName 	description 	commonName
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getType.php";
		String typeIDV = selectAllByID("type", "typeID", currenttypeID, "typeID");
		String typeNameV = selectAllByID("type", "typeID", currenttypeID, "typeName");
		String TdescriptionV = selectAllByID("type", "typeID", currenttypeID, "description");
		String commonNameV = selectAllByID("type", "typeID", currenttypeID, "commonName");
		
		
		t.addCurrentType(typeIDV, typeNameV, TdescriptionV, commonNameV);
		t.addType(databaseURL);

		for (int spinnerI = 0; spinnerI < t.getSize(); spinnerI++) {
			typeSpinneritems.add(t.getType(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> TypeAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, typeSpinneritems);
		TypeAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpin.setAdapter(TypeAA);
		// /]type

		// /[criteria crID 	characteristic 	description 	photo
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getCriteria.php";
		
		String crIDV = selectAllByID("criteria", "crID", currentcrID, "crID");
		String characteristicV = selectAllByID("criteria", "crID", currentcrID, "characteristic");
		String CdescriptionV = selectAllByID("criteria", "crID", currentcrID, "description");
		String photoV = selectAllByID("criteria", "crID", currentcrID, "photo");
		
		
		c.addCurrentCriteria(crIDV, characteristicV, CdescriptionV, photoV);		
		c.addCriteria(databaseURL);

		for (int spinnerI = 0; spinnerI < c.getSize(); spinnerI++) {
			criteriaSpinneritems.add(c.getCriteria(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> CriteriaAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, criteriaSpinneritems);
		CriteriaAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		criteriaSpin.setAdapter(CriteriaAA);
		// /]criteria
		
		
		buttonUpdate.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				String inputTreeID ;
				int inputDBH, inputHeight, inputCrownSpread, inputEstimatedAge;
				String inputLocation;
				double inputLongitude, inputLatitude;
				// String x = new String(""+spin.getSelectedItem());
				// String x = new String("" + spin.getSelectedItem());

				
				try {
					String inputstatusID = new String(i.searchStatusIDByStatus(""
							+ spin.getSelectedItem()));
					String inputdistID = new String(d.searchdistIDBydistName(""
							+ distSpin.getSelectedItem()));
					String inputtypeID = new String(t.searchTypeIDByTypeName(""
							+ typeSpin.getSelectedItem()));
					String inputcriteriaID = new String(c.searchCriteriaIDBycriteria(""
							+ criteriaSpin.getSelectedItem()));
					//toastMsg(inputstatusID + '\n' + inputdistID + '\n' + inputtypeID + '\n' + inputcriteriaID);

					
					inputTreeID = editTreeID.getText().toString();
					inputDBH = Integer.parseInt(editDBH.getText().toString()); 
					inputHeight = Integer.parseInt(editHeight.getText().toString()); 
					inputCrownSpread = Integer.parseInt(editCrownSpread.getText().toString()); 
					inputEstimatedAge = Integer.parseInt(editEstimatedAge.getText().toString());
					inputLocation = editLocation.getText().toString();
					inputLongitude = Double.parseDouble(editLongitude.getText().toString()); 
					inputLatitude = Double.parseDouble(editLatitude.getText().toString());
					
					///get time and date
					Calendar c = Calendar.getInstance();
			        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					//
					//http://localhost/oldTreeWeb/upDateTree.php?location=home&longitude=1&latitude=2&dbh=99&height=99&crownSpread=99&estimatedAge=99&lastinspectionDate=2012-1-1&typeID=T01&distNo=D01&statusID=ST01&crID=C01&inputTreeID=T0099
					
			        
			        String url = getResources().getString(R.string.serverURL) + "upDateTree.php?" +
			        "location="+inputLocation+"&longitude="+inputLongitude+"&latitude="+inputLatitude
			        +"&dbh="+inputDBH+"&height="+inputHeight+"&crownSpread="+inputCrownSpread
			        +"&estimatedAge="+inputEstimatedAge+"&lastinspectionDate="+df.format(c.getTime())
			        +"&registrationDate="+dRegistrationDate
			        +"&typeID="+inputtypeID+"&distNo="+inputdistID+"&statusID="+inputstatusID+"&crID="+inputcriteriaID+"&inputTreeID="+inputTreeID;
			        		
			        		
					HttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet(url);
					HttpResponse response = client.execute(request);

					String line = "";
					String reply = "";
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(response.getEntity()
									.getContent()));
					while ((line = reader.readLine()) != null) {
						reply += line;
					}
					toastMsg("Tree update Successful");
					reader.close();
					finish();
				} catch (Exception e) {
					toastMsg(""+e);
				}

			}
		}

		);
	}

	public void findViewByID() {
		editTreeID = (EditText) findViewById(R.id.editTreeID);
		editDBH = (EditText) findViewById(R.id.editDBH);
		editHeight = (EditText) findViewById(R.id.editHeight);
		editCrownSpread = (EditText) findViewById(R.id.editCrownSpread);
		editEstimatedAge = (EditText) findViewById(R.id.editEstimatedAge);
		editLocation = (EditText) findViewById(R.id.editLocation);
		editLongitude = (EditText) findViewById(R.id.editLongitude);
		editLatitude = (EditText) findViewById(R.id.editLatitude);
		getLongitudeAndLatitudeButton = (Button) findViewById(R.id.getLongitudeAndLatitudeButton);
	}


	public void selectAllFromDB() {
		String reply;
		try {
			// String url =
			// "http://192.168.1.101/oldTreeWeb/getJsonField.php?Name=Tree tat";

			String url;

			url = getResources().getString(R.string.serverURL)
					+ "getJsonByTreeID.php?inputTreeID=" + treeID;

			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			String line = "";
			reply = "";
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			while ((line = reader.readLine()) != null) {
				reply = line;
			}
			reader.close();
			// makeToast(reply);
			try {

				JSONArray json = new JSONArray(reply);

				// toastMsg(""+json.toString());
				JSONArray jsonArrayB = new JSONArray(json.getString(0));
				String getField = jsonArrayB.getString(0);

				JSONObject jsonField = new JSONObject(getField);

				// makeToast(jsonField.getString("treeID"));

				// jsonField.getString("registrationDate");

				// jsonField.getString("lastinspectionDate")
				/*
				 * jsonField.getString("typeID") jsonField.getString("distNo")
				 * jsonField.getString("statusID") jsonField.getString("crID")
				 */

				editTreeID.setText(jsonField.getString("treeID"));
				editDBH.setText(jsonField.getString("dbh"));
				editHeight.setText(jsonField.getString("height"));
				editCrownSpread.setText(jsonField.getString("crownSpread"));
				editEstimatedAge.setText(jsonField.getString("estimatedAge"));
				editLocation.setText(jsonField.getString("location"));
				editLongitude.setText(jsonField.getString("longitude"));
				editLatitude.setText(jsonField.getString("latitude"));
				
				dRegistrationDate = jsonField.getString("dRegistrationDate");
				currentdistNo = jsonField.getString("distNo");
				currentStatusID = jsonField.getString("statusID");
				currenttypeID = jsonField.getString("typeID");
				currentcrID = jsonField.getString("crID");

				//toastMsg(currentcrID);
			} catch (JSONException e) {
				toastMsg("" + e);
			}

		} catch (Exception e) {
			toastMsg("" + e);
		}

	}

	public void toastMsg(String toast) {
		Toast.makeText(this, toast, Toast.LENGTH_LONG).show();

	}

	public String selectAllByID(String inputTable, String inputField, String inputID, String returnField){
		String field = "" ;
		String reply ;
		
		try {
			// String url =
			// "http://192.168.1.101/oldTreeWeb/getJsonField.php?Name=Tree tat";
///getAllByID.php?inputTable=district&inputField=distNo&inputID=D0001
			
			String url = getResources().getString(R.string.serverURL)
					+ "getAllByID.php?inputTable="+ inputTable +"&inputField="+ inputField + "&inputID=" + inputID;
			// getJsonByTreeID.php
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			String line = "";
			reply = "";
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			while ((line = reader.readLine()) != null) {
				reply = line;
			}
			reader.close();
			try {
				
				JSONArray json = new JSONArray(reply);

				String getField = json.getString(0);
				
				
				JSONObject jsonField = new JSONObject(getField);
				
	            field = jsonField.getString(returnField); 


			} catch (Exception e) {
				toastMsg("" + e);
			}
		} catch (Exception e) {
			toastMsg("" + e);
		}
		
		return field;
	}
	public void onGPS(View view){
		Intent i = new Intent(this, UseGPS_BActivity.class);
		//startActivity(i);
		startActivityForResult(i, REQUEST_CODE);
	}
	
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

}
